package org.yunai.swjg.server.module.item.operation.use;

import org.springframework.stereotype.Component;
import org.yunai.swjg.server.core.constants.SysMessageConstants;
import org.yunai.swjg.server.core.role.Role;
import org.yunai.swjg.server.module.item.Inventory;
import org.yunai.swjg.server.module.item.container.Bag;
import org.yunai.swjg.server.module.item.container.CommonBag;
import org.yunai.swjg.server.module.item.container.EquipmentBag;
import org.yunai.swjg.server.module.item.operation.move.ItemMoveOperations;
import org.yunai.swjg.server.module.item.vo.Item;
import org.yunai.swjg.server.module.player.vo.Player;
import org.yunai.swjg.server.rpc.message.S_C.S_C_SysMessageReq;

import javax.annotation.Resource;

/**
 * 使用装备操作<br />
 * 包括如下操作：
 * <pre>
 *     1. 玩家装上装备
 *     2. 玩家卸下装备
 *     3. 伙伴装上装备
 *     4. 伙伴卸下装备
 * </pre>
 * User: yunai
 * Date: 13-6-6
 * Time: 下午6:42
 */
@Component
public class UseEquipmentOperation extends AbstractItemUseOperation {

    @Resource
    private ItemMoveOperations itemMoveOperations;

    @Override
    public boolean isSuitable(Player player, Item item, int targetId) {
        return item.isEquipment();
    }

    /**
     * 判断玩家/伙伴是否存在
     *
     * @param player   玩家信息
     * @param item     道具
     * @param targetId 玩家/伙伴编号
     * @param param    无用参数
     * @return 是否可以使用
     */
    @Override
    protected boolean canUseImpl(Player player, Item item, int targetId, int param) {
        Role role = player.getRole(targetId);
        if (role == null) {
            player.message(new S_C_SysMessageReq(SysMessageConstants.COMMON_ROLE_NOT_FOUND));
            return false;
        }
        return true;
    }

    /**
     * 根据情况来判断是卸载还是装上
     * <pre>
     *     装上：道具在主背包
     *     卸载：道具在装备背包
     * </pre>
     * @param player   玩家信息
     * @param item     道具
     * @param targetId 玩家/伙伴编号
     * @param param    无用参数
     * @return 使用结果
     */
    @Override
    protected boolean useImpl(Player player, Item item, int targetId, int param) {
        Inventory inventory = player.getInventory();
        CommonBag toBag;
        int toIndex;
        switch (item.getBagType()) {
            case PRIM: // 装备
                toBag = inventory.getBag(targetId, Bag.BagType.EQUIPMENT);
                toIndex = EquipmentBag.getPosition(item.getType());
                break;
            case EQUIPMENT: // 卸载
                toBag = inventory.getBag(player.getId(), Bag.BagType.PRIM);
                toIndex = toBag.getFirstEmptyIndex();
                break;
            default:
                return false;
        }
        return itemMoveOperations.getSuitableOperation(player, item, toBag, toIndex)
                .move(player, item, toBag, toIndex);
    }

}